<template>
  <view class="container">
    <view class="login-form">
      <!-- 标题根据模式动态切换 -->
      <view class="title">{{ isLoginMode ? '用户登录' : '用户注册' }}</view>

      <view class="input-group">
        <input class="input" type="number" v-model="phoneNum" placeholder="请输入手机号" style="width: auto;height: auto" />
      </view>
      <view class="input-group">
        <input class="input" type="password" v-model="password" placeholder="请输入密码" style="width: auto;height: auto" />
      </view>
      <!-- “确认密码”输入框仅在注册模式下显示 -->
      <view class="input-group" v-if="!isLoginMode">
        <input class="input" type="password" v-model="confirmPassword" placeholder="请再次输入密码" style="width: auto;height: auto" />
      </view>

      <!-- 验证码输入框，仅在注册模式下显示 -->
      <view class="input-group verification-code-group" v-if="!isLoginMode">
        <input class="input" type="number" v-model="verificationCode" placeholder="请输入验证码" style="width: auto;height: auto" />
        <button class="code-button" @click="sendVerificationCode" :disabled="isCodeSent">
          {{ isCodeSent ? `${countdown}s` : '获取验证码' }}
        </button>
      </view>

      <!-- 按钮的文字和功能根据模式切换 -->
      <button class="login-button" @click="handleSubmit">{{ isLoginMode ? '登录' : '注册' }}</button>

      <!-- 切换登录/注册模式的链接 -->
      <view class="toggle-container">
        <text class="toggle-text" @click="toggleMode">
          {{ isLoginMode ? '没有账号？立即注册' : '已有账号？立即登录' }}
        </text>
      </view>
    </view>
  </view>
</template>

<script>
// 假设你有一个API文件来处理用户相关的请求
// import { Login, Register } from '../../api/user';

import {login, register, sendCode} from "../../api/user";
import {mapState} from 'vuex';
export default {
  computed: {
    ...mapState(['userInfo']),
  },
  data() {
    return {
      isLoginMode: true, // true 为登录模式, false 为注册模式
      phoneNum: '',
      password: '',
      confirmPassword: '',
      verificationCode: '',
      isCodeSent: false,
      countdown: 60,
      timer: null
    }
  },
  beforeDestroy() {
    // 组件销毁前清除定时器，防止内存泄漏
    clearInterval(this.timer);
  },
  methods: {
    // 切换模式
    toggleMode() {
      this.isLoginMode = !this.isLoginMode;
      // 清空所有输入和状态
      this.phoneNum = '';
      this.password = '';
      this.confirmPassword = '';
      this.verificationCode = '';
      if (this.timer) {
        clearInterval(this.timer);
        this.isCodeSent = false;
        this.countdown = 60;
      }
    },
    // 发送验证码
    async sendVerificationCode() {
      // 简单的前端手机号校验
      if (!/^1[3-9]\d{9}$/.test(this.phoneNum)) {
        uni.showToast({ title: '请输入有效的手机号', icon: 'none' });
        return;
      }

      this.isCodeSent = true;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
          this.isCodeSent = false;
          this.countdown = 60;
        }
      }, 1000);

      try {
        let {data: res} = await sendCode(this.phoneNum);
        // 使用 res 变量避免与 data() 中的 data 冲突
        if (res.code === 200) {
          uni.showToast({ title: res.msg || '验证码发送成功', icon: 'success' });
        } else {
          uni.showToast({ title: res.msg || '发送失败，请重试', icon: 'none' });
          // 发送失败时重置按钮状态
          clearInterval(this.timer);
          this.isCodeSent = false;
          this.countdown = 60;
        }
      } catch (error) {
        console.error("发送验证码异常", error);
        uni.showToast({ title: '网络请求失败', icon: 'none' });
        // 异常时重置按钮状态
        clearInterval(this.timer);
        this.isCodeSent = false;
        this.countdown = 60;
      }
    },
    // 处理提交（登录或注册）
    async handleSubmit() {
      if (this.isLoginMode) {
        this.handleLogin();
      } else {
        this.handleRegister();
      }
    },
    // 处理登录
    async handleLogin() {
      if (!this.phoneNum || !this.password) {
        uni.showToast({title: '请输入手机号和密码', icon: 'none'});
        return;
      }
      uni.showLoading({title: '登录中...'});

      try {
        let {data: res} = await login({phoneNum: this.phoneNum, password: this.password});
        uni.hideLoading();

        if (res.code === 200) {
          uni.showToast({title: '登录成功', icon: 'success', duration: 1500});
          console.log(res);
          this.$store.commit('setUserInfo', res.data.resident);
          uni.setStorageSync('token', res.data.token);

          setTimeout(() => {
            console.log("准备跳转到首页...");
            uni.switchTab({url: '/pages/index/index'});
          }, 1500);

        } else {
          // 使用后台返回的错误信息，更友好
          uni.showToast({title: res.msg || '登录失败，请检查账号密码', icon: 'none'});
        }
      } catch (error) {
        uni.hideLoading();
        console.error("登录异常", error);
        uni.showToast({title: '网络请求失败', icon: 'none'});
      }
    },
    // 处理注册
    async handleRegister() {
      if (!this.phoneNum || !this.password || !this.confirmPassword || !this.verificationCode) {
        uni.showToast({title: '请填写所有注册信息', icon: 'none'});
        return;
      }
      if (this.password !== this.confirmPassword) {
        uni.showToast({title: '两次输入的密码不一致', icon: 'none'});
        return;
      }

      uni.showLoading({ title: '注册中...' });

      try {
        let {data: res} = await register({phoneNum: this.phoneNum, password: this.password, code: this.verificationCode, roleId: 4});
        uni.hideLoading();

        if (res.code === 200) {
          uni.showToast({title: '注册成功！请登录', icon: 'success', duration: 2000});

          // 【修改点】注册成功后，不再跳转页面，而是直接切换到登录模式
          setTimeout(() => {
            this.toggleMode();
          }, 2000);

        } else {
          // 使用后台返回的错误信息
          uni.showToast({title: res.msg || '注册失败', icon: 'none'});
        }
      } catch(error) {
        uni.hideLoading();
        console.error("注册异常", error);
        uni.showToast({title: '网络请求失败', icon: 'none'});
      }
    }
  }
}
</script>

<style>
/* 页面容器样式 */
.container {
  display: flex;
  flex-direction: column;
  align-items: center; /* 水平居中 */
  justify-content: center; /* 垂直居中 */
  min-height: 100vh;
  padding: 40rpx;
  box-sizing: border-box; /* 让padding不影响总宽高 */
  background: linear-gradient(135deg, #71b7e6, #9b59b6);
}

/* 登录表单样式 */
.login-form {
  width: 100%;
  max-width: 600rpx; /* 在大屏幕上限制最大宽度 */
  background-color: rgba(255, 255, 255, 0.9); /* 半透明白色背景，更有质感 */
  padding: 60rpx 40rpx;
  border-radius: 20rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.15);
}

/* 标题样式 */
.title {
  font-size: 40rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 60rpx;
  color: #333;
}

/* 输入框组样式 */
.input-group {
  margin-bottom: 40rpx;
}

/* 输入框样式 */
.input {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  outline: none;
  appearance: none;
  -webkit-appearance: none;
  transition: border-color 0.3s;
}

.input:focus {
  border-color: #79abff;
}

/* 验证码输入组样式 */
.verification-code-group {
  display: flex;
  align-items: center;
}

.verification-code-group .input {
  flex-grow: 1;
  margin-right: 20rpx;
}

/* 获取验证码按钮样式 */
.code-button {
  padding: 20rpx;
  font-size: 26rpx;
  background-color: #79abff;
  color: white;
  border: none;
  border-radius: 10rpx;
  white-space: nowrap;
  flex-shrink: 0;
  line-height: 1.5; /* 确保文字垂直居中 */
}

.code-button:active {
  background-color: #5c8fec;
}

.code-button[disabled] {
  background-color: #ccc;
  color: #888;
}


/* 主按钮样式 */
.login-button {
  width: 100%;
  padding: 22rpx;
  background-color: #79abff;
  color: white;
  border: none;
  border-radius: 10rpx;
  font-size: 32rpx;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
}

.login-button:active {
  background-color: #5c8fec;
  transform: scale(0.98);
}

/* 切换模式容器样式 */
.toggle-container {
  margin-top: 40rpx;
  text-align: center;
}

/* 切换模式文字样式 */
.toggle-text {
  color: #555;
  font-size: 26rpx;
  cursor: pointer;
}

.toggle-text:hover {
  text-decoration: underline;
}
</style>

